package com.bw.apps.local

import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.apps.local.entity.LocalAppsEntity
import com.bw.apps.local.entity.LocalAppsState
import com.bw.common.mvi.BaseViewModel
import io.virtualapp.hook_sdk.app.InstallAppUtils
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

class LocalAppsViewModel : BaseViewModel<LocalAppsRepo,LocalAppsState>(){

    override fun createRepo(): LocalAppsRepo {
        return LocalAppsRepo()
    }

    override fun createState(): LocalAppsState {
        return LocalAppsState(false,ArrayList())
    }

    //查询本地应用方法
    fun selLocalApps(){
        viewModelScope.launch {
            repo.selInstallApps().onStart { mutableContainer.updateRequestState { copy(request = true) } }
                .catch { mutableContainer.updateRequestState { copy(request = false,erro = true) } }
                .onCompletion { mutableContainer.updateRequestState { copy(request = false,erro = false, complate = true) } }
                .collect{
                    if (it.isEmpty()){
                        mutableContainer.updateRequestState { copy(request = false,erro = true) }
                        return@collect
                    }
                    mutableContainer.updateUiState { copy(localAppState = true, datas = it) }
                }
        }
    }

    //卸载本地应用方法
    fun unInstallApp(datas : List<LocalAppsEntity>){
        val packages = ArrayList<String>()
        datas.forEach {
            if (it.edtFlag)
                packages.add(it.packageName)
        }
        val flag = InstallAppUtils().unInstallApps(packages)
        if (flag){
            selLocalApps()
        }else
            ToastUtils.showShort("卸载失败")
    }
}